package com.digitalchina.lxnsy.activity.old;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessAccount;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.PointVO;
import com.digitalchina.lxnsy.entity.UserVO;
import com.digitalchina.lxnsy.toolkit.ActivityTaskManager;
import com.digitalchina.lxnsy.toolkit.DateStyle;
import com.digitalchina.lxnsy.toolkit.DateUtil;
import com.digitalchina.lxnsy.toolkit.EncryptUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.toolkit.Utils;
import com.digitalchina.lxnsy.widget.EditTextWithClear;
import com.digitalchina.lxnsy.xml.UserXML;

import java.io.Serializable;
import java.util.List;
import java.util.Set;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;


import static com.digitalchina.lxnsy.constant.Constant.MSG_SET_ALIAS;


/**
 * ================================================
 * 项目名称：bigdata
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：白彦东
 * 创建时间：2016/12/19 19:25
 * 修改备注：
 * ================================================
 */

public class LoginActivity extends BaseActivity {


    @Bind(R.id.login_et_user_name)
    EditTextWithClear loginEtUserName;
    @Bind(R.id.login_et_user_pwd)
    EditTextWithClear loginEtUserPwd;
    @Bind(R.id.login_btn_login)
    Button loginBtnLogin;
    @Bind(R.id.login_tv_forgot_pwd)
    TextView loginTvForgotPwd;
    private UserVO userVO;

    @Override
    public void setLayout() {
        setTitle("登录");
        setRightText("注册");
        setContentLayout(R.layout.activity_login);
    }

    @Override
    public void initMember() {

        if (getIntent().hasExtra("logout")) {
            mIvBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    GotoUtil.gotoActivity(LoginActivity.this, MainActivity.class, true);
                }
            });
        }
    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                dismissDialog();
                switch (msg.what) {
                    case MSG.MSG_LOGIN_SUCCESS:   // 登录成功
                        callBack(msg.obj);
                        break;
                    case MSG.MSG_LOGIN_FAILED:
                        showToast(msg.obj.toString());
                        break;
                    case MSG_SET_ALIAS:
                        LogUtils.e("Set alias in handler.");
                        JPushInterface.setAliasAndTags(getApplicationContext(), (String) msg.obj, null, mAliasCallback);
                        break;
                }
            }

        };
    }

    private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

        @Override
        public void gotResult(int code, String alias, Set<String> tags) {
            String logs;
            switch (code) {
                case 0:
                    logs = "Set tag and alias success";
                    LogUtils.e(logs);
                    break;

                case 6002:
                    logs = "Failed to set alias and tags due to timeout. Try again after 60s.";
                    LogUtils.e(logs);
                    if (Utils.isConnected(getApplicationContext())) {
                        mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SET_ALIAS, alias), 1000 * 60);
                    } else {
                        LogUtils.e("No network");
                    }
                    break;

                default:
                    logs = "Failed with errorCode = " + code;
                    LogUtils.e(logs);
            }

        }

    };


    @Override
    public void callBack(Object object) {

        userVO = FastJsonUtil.getBean(object.toString(), "body", "", UserVO.class);
        userVO.setLoginName(StringUtil.getEditText(loginEtUserName));
        userVO.setInitialPassword(EncryptUtil.SHA1(StringUtil.getEditText(loginEtUserPwd)));

        if (!StringUtil.isStrEmpty(userVO.getHasSettingRole()) && userVO.getHasSettingRole().equals("0")) {
            GotoUtil.gotoActivity(LoginActivity.this, LoginSelectTypeActivity.class, true, "userVO", userVO);
            return;
        }

        List<PointVO> pointVOList = FastJsonUtil.getListBean(object.toString(), "body", "rewardPointDetailList", PointVO.class);


        if (userVO == null) {
            showToast("登录失败：用户信息异常");
            return;
        }

        if (userVO.getUserType() == null || (!userVO.getUserType().equals(Constant.USER_TYPE_PERSON)
                && !userVO.getUserType().equals(Constant.USER_TYPE_EXPERT))) { //除了个人用户和专家 其他无登录权限
            new MaterialDialog.Builder(this)
                    .title("提示")
                    .content("对不起，该用户没有权限！")
                    .positiveText("确定")
                    .show();
            return;
        }

        showToast("登录成功");


        //个人信息存储
        UserXML.setUserVO(this, userVO);
        setAlias(userVO.getUseraccid().replace("-", ""));

//        baseDWebView.callHandler("userId",new String[]{userVO.getUseraccid()});


        // 注册为个人用户
        if (userVO.getUserType().equals(Constant.USER_TYPE_PERSON) || (userVO.getUserType().equals(Constant.USER_TYPE_EXPERT)) && !userVO.getIsAudit().equals("3")) {

            UserXML.setTodayLogin(LoginActivity.this, DateUtil.getCurrentDate(DateStyle.YYYY_MM_DD));
            UserXML.setLoginStatus(LoginActivity.this, UserXML.USER_IS_LOGIN_VALUE);



            if (ActivityTaskManager.getInstance().size() > 1) {
                Intent i = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("pointVOList", (Serializable) pointVOList);
                i.putExtras(bundle);
                setResult(1, i);
                finish();
            } else {
                GotoUtil.gotoActivity(LoginActivity.this, MainActivity.class, true, "pointVOList", pointVOList);
            }
        } else {
            // 注册为专家用户
            GotoUtil.gotoActivity(LoginActivity.this, SaveExpertInfoActivity.class, true);
        }
    }

    private void setAlias(String alias) {
        LogUtils.e(alias);
        if (TextUtils.isEmpty(alias)) {
            LogUtils.e("alias is empty");
            return;
        }
        if (!Utils.isValidTagAndAlias(alias)) {
            LogUtils.e("alias is not valid");
            return;
        }

        //调用JPush API设置Alias
        mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, alias));
    }

    @Override
    public void rightOnClick() {
        GotoUtil.gotoActivity(this, RegisterTypeSelectActivity.class, true);
    }

    @OnClick({R.id.login_btn_login, R.id.login_tv_forgot_pwd, R.id.login_tv_login_code})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_btn_login:
                login(); // 登录
                break;
            case R.id.login_tv_forgot_pwd:
                GotoUtil.gotoActivity(LoginActivity.this, ForgetPasswordStepOneActivity.class);
                break;
            case R.id.login_tv_login_code:
                GotoUtil.gotoActivity(LoginActivity.this, LoginCodeActivity.class, true);
                break;
        }
    }

    /**
     * 登录
     */
    private void login() {

        String loginName = StringUtil.getEditText(loginEtUserName);
        String loginPwd = StringUtil.getEditText(loginEtUserPwd);

        if (StringUtil.isStrEmpty(loginName)) {
            showToast("请输入用户名");
            return;
        }

        if (StringUtil.isStrEmpty(loginPwd)) {
            showToast("请输入密码");
            return;
        }

        showDialog("登录中,请稍候...");
        BusinessAccount.login(this, loginName, EncryptUtil.SHA1(loginPwd), mHandler);
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (getIntent().hasExtra("logout") || ActivityTaskManager.getInstance().size() == 1) {
                GotoUtil.gotoActivity(LoginActivity.this, MainActivity.class, true);
            } else
                finish();
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }
}


